package com.example.leo.mycharmingstudent.a0924;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import com.example.leo.mycharmingstudent.R;

public class ContactsActivity extends AppCompatActivity {

    private static final String TAG = "ContactsActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);

        //检查有没有相应权限，读取联系人权限
        int permission = ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_CONTACTS);
        if (permission == PackageManager.PERMISSION_GRANTED) {
            //已经获取了读取联系人权限
            obtainContacts();
        } else {
            //还没有获取读取联系人权限，需要动态申请权限
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.READ_CONTACTS},
                    1000);
        }
    }

    /**
     * 动态申请权限以后，会执行此方法，传回权限申请结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(
            int requestCode,
            @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1000:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    obtainContacts();
                }
                break;
            default:
                Log.e(TAG, "onRequestPermissionsResult: " +
                        "I don't know this request code!please check!");
                break;
        }
    }

    /**
     * 获取手机联系人
     * Caused by: java.lang.SecurityException: Permission Denial:
     * opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord{7f46999 8860:com.example.leo.mycharmingstudent/u0a73} (pid=8860, uid=10073)
     * requires android.permission.READ_CONTACTS or android.permission.WRITE_CONTACTS
     */
    private void obtainContacts() {
        //获取ContentResolver对象，用来操作ContentProvider
        ContentResolver contentResolver = getContentResolver();
        Cursor cursor1 = contentResolver.query(
                ContactsContract.Contacts.CONTENT_URI,
                null,
                null,
                null,
                null);
        while (cursor1.moveToNext()) {
            //getString的参数是：指定列的索引
            String name = cursor1.getString(
                    //getColumnIndex获取指定列的索引
                    //getColumnIndex的参数是：列名或者字段名称
                    cursor1.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String _id = cursor1.getString(
                    cursor1.getColumnIndex(ContactsContract.Contacts._ID));
            //根据_id，去另一个ContentProvider中，查询电话号码
            String selections = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?";
            Cursor cursor2 = contentResolver.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    selections,
                    new String[]{_id},
                    null
            );
            //存的联系人电话，可能有多条，所以需要循环取出
            while (cursor2.moveToNext()) {
                String phone = cursor2.getString(
                        cursor2.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//                name += "----" + phone;
                name = name + "----" + phone;
            }
            Log.e(TAG, "obtainContacts: " + name);
        }

    }
}
